<template>
  <div class="m-2">
    <!-- 搜索区域  -->
    <searchFrom exportType="low_order" :searchInfo="searchInfo" @confirmSearch="handleSearch"
                @groupLimit="handleLimit"/>

    <!-- 列表  -->
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'categories_tree'">
          <div class="white-wrap">
            {{ record.categories_tree }}
          </div>
        </template>
        <template v-else-if="column.key === 'title'">
          <div class="white-wrap">
            {{ record.title }}
          </div>
        </template>
        <template v-else-if="column.key === 'limit_reason'">
          <div class="white-wrap">
            {{ record.limit_reason }}
          </div>
        </template>
        <template v-else-if="column.key === 'order_num'">
          <div v-for="i in record.month_order">
            {{ i.month }} 月总单量： {{ getDaysInMonth(i.month, i.order_num) }}
          </div>
        </template>
        <template v-else-if="column.key === 'image'">
          <div v-show="record.image && record.image !== 'https://m.media-amazon.com/images/I/'"
               class="text-center w-full">
            <Image
              :height="150"
              :src="record.image"
            />
          </div>
        </template>
        <template v-if="column.key === 'action'">
          <a-button @click.stop="handleView(record)" type="primary">限制售卖</a-button>
          <br/>
          <Popconfirm placement="left"
                      title="确定要更新单量吗？"
                      ok-text="确定"
                      cancel-text="算了"
                      @confirm="updateOrderNum(record)"
          >
          <a-button type="success">更新单量</a-button>
          </Popconfirm>
        </template>
      </template>
    </BasicTable>
    <LimitModal @register="register" @reload_data="reload_list"/>
    <GroupLimitModal @register="register2" @clear_select="handleClear" @reload_data="reload_list"/>
  </div>
</template>

<script lang="ts" setup>
import {h} from 'vue';
import searchFrom from '/@/components/Custom/MonthSearchFrom.vue'
import {Tag, Image, Popconfirm} from 'ant-design-vue';
import {reactive, ref} from 'vue'
import {BasicTable, useTable, BasicColumn} from '/@/components/Table';
import {getAvgOrder, getProductBySjNameGroup, updateAsinOrder} from "/@/api/demo/product";
import {useModal} from "/@/components/Modal";
import LimitModal from '/@/components/Custom/LimitModal.vue'
import GroupLimitModal from '/@/components/Custom/GroupLimitModal.vue'
import {getLowOrder} from "/@/api/demo/select";
import {setAdminStatus} from "/@/api/demo/system";
import {message} from 'ant-design-vue';

const columns: BasicColumn[] = reactive([
  {
    title: '国家',
    dataIndex: 'country_desc',
    width: 140,
    customRender: ({record}) => {
      const status = record.country_desc
      var color = 'blue'
      switch (status) {
        case '美国':
          color = 'cyan'
          break;
        case '英国':
          color = 'purple'
          break;
        case '欧洲四国':
          color = 'orange'
          break;
        case '加拿大':
          color = 'green'
          break;
        case '日本':
          color = 'pink'
          break;
      }
      return h(Tag, {color: color}, () => status)
    },
  },
  {
    title: 'ASIN',
    dataIndex: 'asin',
    fixed: 'left',
    width: 140
  },
  {
    title: '限制类型',
    dataIndex: 'limit_type_desc',
    width: 150,
    customRender: ({record}) => {
      const limit_type_desc = record.limit_type_desc
      if (limit_type_desc) {
        var color = 'purple'
        return h(Tag, {color: color}, () => limit_type_desc)
      }
    },
  },
  {
    title: '限制原因',
    dataIndex: 'limit_reason',
    width: 200
  },
  {
    title: '在售状态',
    dataIndex: 'status',
    width: 120,
    customRender: ({record}) => {
      const status = record.status
      var color = 'green'
      if (status == '不在售') {
        color = 'red'
      }
      return h(Tag, {color: color}, () => status)
    },
  },

  {
    title: '所属组',
    dataIndex: 'group_name',
    width: 150
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 200
  },
  {
    title: '图片',
    dataIndex: 'image',
    width: 140
  },
  {
    title: 'Amazon分类树',
    dataIndex: 'categories_tree',
    width: 200
  },
  {
    title: '月订单量',
    dataIndex: 'current',
    width: 150
  },
  {
    title: '往期数据',
    dataIndex: 'last_order',
    width: 150
  },
  {
    title: '往期数据',
    dataIndex: 'last_last_order',
    width: 150
  },
  {
    title: '是否同步系统',
    dataIndex: 'has_moved',
    width: 150,
    customRender: ({record}) => {
      const move_system = record.has_moved
      if (move_system) {
        var color = 'green'
        var text = '已同步'
      } else {
        color = 'red'
        text = '未同步'
      }
      return h(Tag, {color: color}, () => text)
    },
  },

  {
    title: '操作人',
    dataIndex: 'nickname',
    width: 200
  },
  {
    title: '限制时间',
    dataIndex: 'limit_time',
    width: 200
  },
]);
const [register, {openModal: openProductModal, setModalProps}] = useModal()
const [register2, {openModal: openProductModal2, setModalProps2}] = useModal()
const searchInfo = reactive<Recordable>({
  page: 1,
  pageSize: 20,
})

function handleView(record: Recordable) {
  openProductModal(true, {
    'asin': record.asin,
    'month': record.month,
    'country_desc': record.country_desc,
    'group_name': record.group_name,
    'limit_type': record.limit_type,
    'limit_reason': record.limit_reason,
  })
}

function updateOrderNum(record: Recordable) {
  updateAsinOrder(record).then(
    () => {
      setTimeout(function () {
        message.success('更新成功！')
        reload()
      }, 200)
    },
    (error) => {
      console.log(error)
    },
  )
}

function reload_list() {
  reload()
}

const [registerTable, {reload, getSelectRowKeys, clearSelectedRowKeys}] = useTable({
  api: getLowOrder,
  columns: columns,
  searchInfo: searchInfo,
  showIndexColumn: false,
  bordered: true,
  showTableSetting: false,
  immediate: false,
  showSelectionBar: true,
  rowKey: '_id',
  rowSelection: {
    type: 'checkbox',
  },
  pagination: {
    onChange: (page, pageSize) => {
      searchInfo.page = page
      searchInfo.pageSize = pageSize
    }
  },
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  },
});

function getPreviousMonths(dateString: string): { lastMonth: string, twoMonthsAgo: string } {
  // 将日期字符串解析为Date对象
  const date = new Date(dateString + '-01'); // 假设输入总是形如YYYY-MM的字符串，我们补全为YYYY-MM-01

  // 计算上个月
  const lastMonth = new Date(date);
  lastMonth.setMonth(lastMonth.getMonth() - 1);

  // 计算上上个月
  const twoMonthsAgo = new Date(date);
  twoMonthsAgo.setMonth(twoMonthsAgo.getMonth() - 2);

  // 格式化日期为YYYY-MM格式
  function formatDate(d: Date): string {
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要+1
    return `${year}-${month}`;
  }

  return {
    lastMonth: formatDate(lastMonth),
    twoMonthsAgo: formatDate(twoMonthsAgo),
  };
}

function handleSearch(formData) {
  const result = getPreviousMonths(formData.month);
  columns[9].title = formData.month;
  columns[10].title = result.lastMonth;
  columns[11].title = result.twoMonthsAgo;

  searchInfo.country = formData.country
  searchInfo.group_name = formData.group_name
  searchInfo.month = formData.month
  searchInfo.month_num = formData.month_num
  searchInfo.is_limit = formData.is_limit
  searchInfo.limit_type = formData.limit_type
  searchInfo.status = formData.status
  searchInfo.asin = formData.asin
  searchInfo.page = 1
  reload()
}

function getDaysInMonth(month_str, orders): number {
  var month_arr = month_str.split('-')
  var year = parseInt(month_arr[0])
  var month = parseInt(month_arr[1])

  const date = new Date(year, month, 0);
  return (orders / date.getDate()).toFixed(2);
}

function handleLimit() {
  const ids = getSelectRowKeys();
  if (ids.length == 0) {
    message.warn('请选择要批量限制的记录！');
  } else {
    openProductModal2(true, {
      'selected_ids': ids,
      'month': searchInfo.month
    })
  }
}

function handleClear() {
  clearSelectedRowKeys();
}

const keepa_detail = (item) => {
  const keepa_url = 'https://keepa.com/#!product/'
  var keepa_detail = item.domain_id + '-' + item._id
  window.open(keepa_url + keepa_detail, '_blank')
}

</script>

<style>
.white-wrap {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}
</style>
